package com.chenwc.rocketmq.example;

import com.chenwc.rocketmq.prop.RocketMqConnectionProperties;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeleteTopics {
    private static final Logger logger = LoggerFactory.getLogger(DeleteTopics.class);

    public static void main(String[] args) {

        RocketMqConnectionProperties properties = new RocketMqConnectionProperties();

        final String topicToDelete = "TopicTest";
        final String nameServerAddr = properties.getNamesrvAddr();
        final String brokerAddr = properties.getBrokerAddr();

        MQClientAPIImpl admin = null;
        try {
            // 配置 AccessKey 和 SecretKey
            SessionCredentials sessionCredentials = new SessionCredentials(properties.getAccessKey(), properties.getSecretKey());
            RPCHook aclHook = new AclClientRPCHook(sessionCredentials);

            ClientConfig config = new ClientConfig();
            config.setNamesrvAddr(nameServerAddr);
            admin = MQClientManager.getInstance().getOrCreateMQClientInstance(config, aclHook).getMQClientAPIImpl();

            admin.start();
            logger.info("Starting to delete topic: {}", topicToDelete);

            // Step 1: Delete topic from NameServer
            admin.deleteTopicInNameServer(nameServerAddr, topicToDelete, 3000);

            // Step 2: Delete topic from Broker
            admin.deleteTopicInBroker(brokerAddr, topicToDelete, 3000);

            logger.info("Topic deleted successfully.");
        } catch (MQClientException | RemotingException e) {
            logger.error("Error occurred while deleting topic: {}", topicToDelete, e);
        } catch (InterruptedException e) {
            logger.error("Interrupted while deleting topic: {}", topicToDelete, e);
        } finally {
            if (admin != null) {
                admin.shutdown();
            }
        }
    }
}
